import { Component, OnInit } from '@angular/core';
import { NavController, Platform, ModalController } from '@ionic/angular';
import { DomSanitizer } from '@angular/platform-browser';
import { HttpService } from 'src/app/service/http.service';
import { UrlService } from 'src/app/service/url.service';
import { ConfigService } from 'src/app/service/config.service';
import { PopwinService } from 'src/app/service/popwin.service';
import * as $ from 'jquery';
import { ToolService } from 'src/app/service/tool.service';
import { Clipboard } from '@ionic-native/clipboard/ngx';
import { Router } from '@angular/router';
import { AccountrechargecardmodalComponent } from '../accountrechargecardmodal/accountrechargecardmodal.component';
import { Storage } from '@ionic/storage';
@Component({
  selector: 'app-accountrecharge',
  templateUrl: './accountrecharge.page.html',
  styleUrls: ['./accountrecharge.page.scss'],
})
export class AccountrechargePage implements OnInit {
  public url: any = "";
  public inputArr = [];
  public payNum = "";//输入的金额
  public wayList: any = [];//支付的大类
  private selectItemData: any;//选中的支付方式的数据
  private noteStr: String = "";//随机数
  public isMarkWin: boolean = false;
  public ewmUrl: String = "";//二维码的图片链接
  public isEwm: Boolean = false;//是否显示二维码
  public cardMsg: any;//银行卡的信息
  public isClick: Boolean = true;//是否单击
  public nickName: String = "";

  public isBankList = false;//是否显示银行卡
  public bankListArr = [];//所有银行卡的列表
  public needBankidArr = [];//哪些需要选中银行卡
  public bankCode = ""; //银行的code码
  public isAccountName = false;//是否有用户姓名
  public accountName = "";
  public isCardNo = false;//是否输入银行卡号
  public cardNo = "";

  //自营或第三方的充值方式
  public rechargeType = [];
  public defaultRechargeType = ""; //选中的方式
  public selfList = []; //自营的银行卡
  public recharegeNote = "";//附言
  public recharegeMsg = { "id": "", "bankname": "", "branchname": "", "name": "", "cardno": "" };
  public recharegeIndex = 0;

  //自营提交的数据
  public accountMoney = "";
  public accountName2 = "";
  public accountNo = "";
  public accountNote = "";
  public selectDate = "";


  constructor(private navCtrl: NavController, private domSanitizer: DomSanitizer, private http: HttpService, private popWin: PopwinService, private plt: Platform, private router: Router, private clipboard: Clipboard,
    private modalCtr: ModalController, private store: Storage) { }

  ngOnInit() {
    // if (this.plt.is("ios")) {
    //   this.url = this.domSanitizer.bypassSecurityTrustResourceUrl(ConfigService.SERVER_PATH + "" + UrlService.OTHER_USERINCASH + "?token=" + $("app-root").attr("token") + "&sessid=" + $("app-root").attr("sessid"));
    // } else {
    //   this.url = this.domSanitizer.bypassSecurityTrustResourceUrl(ConfigService.SERVER_PATH + "" + UrlService.OTHER_USERINCASH + "?token=" + $("app-root").attr("token"));
    // }
    this.getPayData();
    this.getUsername();
    //  console.log("支付的连接", this.url);
  }
  /**
   * 获取支付方式的数据
   */
  getPayData() {
    let that = this;
    this.http.get(UrlService.OTHER_INCASH, { "callback": "JSONP_CALLBACK" }).subscribe(res => {
      let data = res.json();
      ToolService.setEncrypt(data.encrypt);
      if (data.code == ConfigService.SUCCESS_CODE) {
        //成功的逻辑
        let resData = ToolService.aesDecodeToJson(data.data);
        console.log("后台的成功逻辑:", resData);
        that.inputArr = resData.selectMoneyArr;
        that.wayList = that.dealData(resData.wayList, resData.channel_wayList);
        that.noteStr = resData.note;
        that.bankListArr = resData.banks;
        that.needBankidArr = resData.need_bankid;
        that.selfList = resData.selfList;
        that.recharegeMsg = resData.selfList[0];
        that.recharegeNote = resData.note;
        let tempRechargeType = [];
        for (let item in resData.payTop) {
          tempRechargeType.push({ "type": item, "title": resData.payTop[item]['title'] });
          if (resData.payTop[item]['default'] == 1) {
            that.defaultRechargeType = item;
          }
        }
        that.rechargeType = tempRechargeType;
        console.log("处理完成的逻辑:", that.wayList);
      } else if (data.code == ConfigService.FAIL_CODE) {
        that.popWin.toast(data.message);
      } else if (data.code == ConfigService.LOGIN_CODE) {
        that.navCtrl.navigateForward("/login");
      }
    }, error => {
      console.log("error", error);
    });
  }
  /**
   * 数据的拼合
   * @param wayList 类别数组
   * @param channel_wayList 子数组
   */
  dealData(wayList: any[], channel_wayList: any[]) {
    let resArr = [];
    for (let item in wayList) {
      let way_id = wayList[item].id;
      let tempArr = [];
      for (let item1 in channel_wayList) {
        let way_id1 = channel_wayList[item1].way_id;
        if (way_id == way_id1) {
          channel_wayList[item1].active = false;
          tempArr.push(channel_wayList[item1]);
        }
      }
      if (tempArr.length > 0) {
        wayList[item].show = false;
        wayList[item].son_method = tempArr;
        resArr.push(wayList[item]);
      }
    }
    return resArr;
  }

  toggleGroup(item) {
    item.show = !item.show;
  }

  isGroupShown(item) {
    return item.show;
  }
  /**
   * 选择支付方式的事件
   * @param item 选中支付方式的数据
   */
  selectItem(item, itemsonId) {
    if ($("#son-item-" + itemsonId).hasClass("active")) {
      $(".son-item").removeClass("active");
      this.selectItemData = "";
      this.isBankList = false;
      return;
    }
    $(".son-item").removeClass("active");
    $("#son-item-" + itemsonId).addClass("active");
    this.selectItemData = "";
    this.selectItemData = item;
    console.log(item);
    if (this.isExitVal(this.needBankidArr, item.id)) {
      this.isBankList = true;
    } else {
      this.isBankList = false;
    }
    this.payNum = ToolService.moneyFormat(this.payNum + "", true, true);
  }
  /**
   * 判断一维数组中是否存在值
   * @param arr 目标一维数组
   * @param val 目标的值
   */
  isExitVal(arr, val) {
    let isExit = false;
    if (arr.indexOf(val) > -1) {
      isExit = true;
    }
    return isExit;
  }
  /**
   * 点击确定支付
   */
  onSubmitPay() {
    if (ToolService.isEmpty(this.selectItemData)) {
      this.popWin.toast("请选择支付方式");
      return;
    }
    if (ToolService.isEmpty(this.payNum)) {
      this.popWin.toast("请输入合法的数据");
      return;
    }
    if (this.isBankList && ToolService.isEmpty(this.bankCode)) {
      this.popWin.toast("请选择银行");
      return;
    }
    if (this.isBankList && !ToolService.isEmpty(this.bankCode) && this.isAccountName && ToolService.isEmpty(this.accountName)) {
      this.popWin.toast("请填写持卡人姓名");
      return;
    }
    if (this.isBankList && !ToolService.isEmpty(this.bankCode) && this.isCardNo && ToolService.isEmpty(this.cardNo)) {
      this.popWin.toast("请填写持卡人卡号");
      return;
    }

    if (parseFloat(this.selectItemData.min) < 1 && parseFloat(this.payNum) < 1) {
      this.popWin.toast("最小充值1元");
      return;
    } else if (parseFloat(this.selectItemData.min) > 1) {
      if (parseFloat(this.payNum) < parseFloat(this.selectItemData.min)) {
        this.popWin.toast("最小充值" + this.selectItemData.min + "元");
        return;
      } else if (parseFloat(this.payNum) > parseFloat(this.selectItemData.max)) {
        this.popWin.toast("最大充值" + this.selectItemData.max + "元");
        return;
      }
    }
    let way_id = this.selectItemData.way_id;
    let is_url = this.selectItemData.is_url;
    if (way_id == 1 || way_id == "1" || is_url == 1 || is_url == "1") { //在线网银
      let param = "{\"num\":\"" + this.payNum + "\",\"wid\":\"" + this.selectItemData.channel_way_id + "\",\"code\":\"" + this.bankCode + "\",\"account_name\":\"" + this.accountName + "\",\"account_no\":\"" + this.cardNo + "\"}";
      this.router.navigate(['/accountrechargeweb'], {
        queryParams: { "p": ToolService.paramAESEncrypt(param) }
      });
    } else if (way_id == '2' || way_id == 2) {//扫码支付
      if (this.isClick) {
        this.payNet(this.payNum, this.selectItemData.channel_way_id, way_id, this.noteStr, this.cardNo);
        this.isClick = false;
      }
    } else if (way_id == '4' || way_id == 4) { //转帐支付
      if (this.isClick) {
        this.isClick = false;
        this.rechargeCard(this.selectItemData);
      }
    } else {
      this.popWin.toast("程序猿在加急处理中...");
    }
  }

  async rechargeCard(dataParam) {
    this.isClick = true;
    const addModal = await this.modalCtr.create({
      component: AccountrechargecardmodalComponent,
      componentProps: {
        params: dataParam,
        cash: this.payNum
      }
    })
    await addModal.present();
    //监听销毁的事件，接收返回的值
    const { data } = await addModal.onDidDismiss();
    if (!ToolService.isEmpty(data)) {
      let cardMsg = "{\"userName\":\"" + data.userName + "\",\"bankName\":\"" + data.bankName + "\",\"cardId\":\"" + data.cardId + "\",\"depostitTime\":\"" + data.depostitTime + "\"}";
      this.payNet(this.payNum, this.selectItemData.channel_way_id, 4, this.noteStr, this.cardNo, cardMsg);
    }
  }
  /**
   * 限定输入合法的取整数字
   */
  inputChangeVal() {
    this.payNum = ToolService.moneyFormat(this.payNum + "", true, true);
  }
  inputCardNoChangeVal() {
    this.cardNo = ToolService.moneyFormat(this.cardNo + "", true, true);
  }


  payNet(money, channel_way_id, way_id, note, cardNo = "", cardMsg?: any) {
    let that = this;
    let obj = "{\"money\":\"" + money + "\",\"channel_way_id\":\"" + channel_way_id + "\",\"note\":\"" + note + "\"}";
    if (!ToolService.isEmpty(cardMsg) && !ToolService.isEmpty(cardNo)) {
      obj = "{\"money\":\"" + money + "\",\"channel_way_id\":\"" + channel_way_id + "\",\"note\":\"" + note + "\",\"bank_info\":" + cardMsg + ",\"account_no\":" + cardNo + "}";
    }
    if (!ToolService.isEmpty(cardMsg) && ToolService.isEmpty(cardNo)) {
      obj = "{\"money\":\"" + money + "\",\"channel_way_id\":\"" + channel_way_id + "\",\"note\":\"" + note + "\",\"bank_info\":" + cardMsg + "}";
    }
    if (ToolService.isEmpty(cardMsg) && !ToolService.isEmpty(cardNo)) {
      obj = "{\"money\":\"" + money + "\",\"channel_way_id\":\"" + channel_way_id + "\",\"note\":\"" + note + "\",\"account_no\":" + cardNo + "}";
    }
    console.log("---------传递的参数:", obj);
    this.http.get(UrlService.OTHER_INCASH2, { "callback": "JSONP_CALLBACK", "data": ToolService.aesEncode(obj) }).subscribe(res => {
      let data = res.json();
      ToolService.setEncrypt(data.encrypt);
      that.isClick = true;
      if (data.code == ConfigService.SUCCESS_CODE) {
        //成功的逻辑
        let resData = ToolService.aesDecodeToJson(data.data);
        console.log("成功的逻辑:", resData);
        if (ToolService.isEmpty(resData)) {
          that.popWin.toast("该方式暂不能支付");
          return;
        }
        if (resData.state == '1' || resData.state == 1) {
          that.popWin.toast(resData.message);
          return;
        }
        that.isMarkWin = false;
        that.isEwm = false;
        if (way_id == '2' || way_id == 2) {//扫码支付
          that.isMarkWin = true;
          that.isEwm = true;
          that.ewmUrl = resData.url;
        } else if (way_id == '4' || way_id == 4) {
          if (!ToolService.isEmpty(resData.order_no)) {
            that.popWin.toast("订单确定成功");
            return;
          }
        }
      } else if (data.code == ConfigService.FAIL_CODE) {
        that.popWin.toast(data.message);
      } else if (data.code == ConfigService.LOGIN_CODE) {
        that.navCtrl.navigateForward("/login");
      }
    }, error => {
      that.isClick = true;
      console.log("error", error);
    });
  }
  /**
   * 关闭蒙版
   */
  onCloseMask() {
    this.isMarkWin = false;
  }
  /**
   * 复制卡号
   */
  onCopyCardNo(text: any) {
    this.copyFun(text);
  }

  copyFun(text: any) {
    if (this.plt.is("cordova")) {
      this.clipboard.copy(text).then(() => {
        this.popWin.toast("复制成功");
      });
    } else {
      let save = function (e) {
        e.clipboardData.setData('text/plain', text);   //保存到剪切板
        e.preventDefault(); //阻止默认行为
      }
      document.addEventListener('copy', save);
      document.execCommand("copy");     //使文档处于可编辑状态，否则无效
      this.popWin.toast("复制成功");
    }
  }
  /**
   * 选择默认的值
   */
  onSelectDefaultVal(val) {
    this.payNum = val;
  }
  /**
   * 页面的放回操作
   */
  backClick() {
    this.navCtrl.navigateBack("/tabs/recharge");
  }
  /**
   * 点击客服跳转到个人中心页面
   */
  toKefu() {
    this.navCtrl.navigateRoot("/tabs/my");
  }
  /**
   * 获取用户名
   */
  getUsername() {
    this.store.get(ConfigService.USERINFO_KEY).then((data) => {
      let tempUserInfo = data;
      if (!ToolService.isEmpty(tempUserInfo)) {
        let userInfo = tempUserInfo;
        this.nickName = userInfo.uinfo.username;
      }
    });
  }

  selectBank() {
    console.log("选中的code==", this.bankCode);
    console.log(this.selectItemData.need_cardno === 1 || this.selectItemData.need_cardno === "1")
    let tempCode = this.bankCode.toLocaleUpperCase();
    if (tempCode == "WEBMM" || tempCode == "ALIPAY") {
      this.isAccountName = false;
      this.accountName = "";
    } else {
      this.isAccountName = true;
      if (this.selectItemData.need_cardno === 1 || this.selectItemData.need_cardno === "1") {
        this.isCardNo = true;
      } else {
        this.isCardNo = false;
      }
    }
  }
  //切换账户方式
  onChangeRechargeType(typeVal) {
    this.defaultRechargeType = typeVal;
  }
  //选中自营的账户
  onChangeAccount(index) {
    if (this.recharegeIndex != index) {
      this.recharegeMsg = this.selfList[index];
      this.recharegeIndex = index;
    }
  }
  inputAccountNoVal() {
    this.accountNo = ToolService.moneyFormat(this.accountNo + "", true, true);
  }
  inputAccountMoneyVal() {
    this.accountMoney = ToolService.moneyFormat(this.accountMoney + "", true, false);
  }

  onRechargeFinish() {
    console.log("accountMoney:" + this.accountMoney + "-accountName2:" + this.accountName2 + "-accountNo:" + this.accountNo + "-accountNote:" + this.accountNote + "-selectDate:" + this.selectDate.substr(0, 10));
    let that = this;
    if(ToolService.isEmpty(this.recharegeMsg)){
      that.popWin.toast("请选择收款账户");
      return;
    }
    if(ToolService.isEmpty(this.accountMoney)){
      that.popWin.toast("请填写汇款金额");
      return;
    }
    if(ToolService.isEmpty(this.accountName2)){
      that.popWin.toast("请填写汇款姓名");
      return;
    }
    if(ToolService.isEmpty(this.accountNo)){
      that.popWin.toast("请填写汇款账号");
      return;
    }
    if(ToolService.isEmpty(this.accountNote)){
      that.popWin.toast("请填写附言");
      return;
    }
    if(ToolService.isEmpty(this.selectDate)){
      that.popWin.toast("请选择打款时间");
      return;
    }
    let obj = "{\"card_id\":\"" + this.recharegeMsg['id'] + "\",\"money\":\"" + this.accountMoney + "\",\"account_name\":\"" + this.accountName2 + "\",\"account_no\":\"" + this.accountNo + "\",\"bill_time\":\"" + this.selectDate.substr(0, 10) + "\",\"note\":\"" + this.accountNote + "\"}";;
    this.http.get(UrlService.OTHER_INCASH3, { "callback": "JSONP_CALLBACK", "data": ToolService.aesEncode(obj) }).subscribe(res => {
      let data = res.json();
      ToolService.setEncrypt(data.encrypt);
      if (data.code == ConfigService.SUCCESS_CODE) {
        //成功的逻辑
        that.accountMoney = "";
        that.accountName2 = "";
        that.accountNo = "";
        that.accountNote = "";
        that.selectDate = "";
        that.popWin.toast(data.message);
      } else if (data.code == ConfigService.FAIL_CODE) {
        that.popWin.toast(data.message);
      } else if (data.code == ConfigService.LOGIN_CODE) {
        that.navCtrl.navigateForward("/login");
      }
    }, error => {
      console.log("error", error);
    });
  }

}
